/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.workcell.workdata.im.service.impl;

import com.workcell.workdata.im.component.holder.UidHolder;
import com.workcell.workdata.im.entity.Note;
import com.workcell.workdata.im.model.request.NoteAddRequest;
import com.workcell.workdata.im.model.request.NoteUpdateRequest;
import com.workcell.workdata.im.model.vo.NoteVO;
import com.workcell.workdata.im.repository.NoteRepository;
import com.workcell.workdata.im.service.NoteService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NoteServiceImpl implements NoteService {

	@Resource
	private NoteRepository noteRepository;

	@Override
	public long add(NoteAddRequest request) {

		Note note = new Note();
		note.setContent(request.getContent());
		note.setFormat(request.getFormat());
		note.setTitle(request.getTitle());
		note.setExtra(request.getExtra());
		note.setText(request.getText());
		note.setUid(UidHolder.getUid());
		note.setCreateTime(new Date());
		note.setUpdateTime(new Date());

		noteRepository.saveAndFlush(note);

		return note.getId();
	}

	@Override
	public void update(NoteUpdateRequest request) {

		Note target = noteRepository.findById(request.getId()).orElse(null);

		if (target == null || !target.getUid().equals(UidHolder.getUid())){
			return;
		}

		target.setUpdateTime(new Date());
		target.setText(request.getText());
		target.setContent(request.getContent());
		target.setFormat(request.getFormat());
		target.setTitle(request.getTitle());
		target.setExtra(request.getExtra());

		noteRepository.saveAndFlush(target);
	}

	@Override
	public void delete(long id) {
		noteRepository.deleteById(id);
	}

	@Override
	public List<NoteVO> findList(long uid) {
		return noteRepository.findList(uid).stream().map(NoteVO::of).collect(Collectors.toList());
	}

}
